<template>
	<view class="wrap">
		<template v-if="isLogin">
			<view v-if="cartList.length" class="cartcartList u-p-b-80">
				<!-- <view class="cartcartList u-p-b-80"> -->
				<view class="cartGoods u-flex u-p-15" v-for="goods in cartList" :key="goods._id">
					<view>
						<u-checkbox v-model="goods.isCheck" size="40" shape="circle" @change="checkChange"
							:name="goods._id"></u-checkbox>
					</view>
					<view class="goodsInfo u-flex u-p-10">
						<view>
							<u-image border-radius="15" width="200rpx" height="200rpx" :src="goods.indexUrl">
							</u-image>
						</view>
						<view class="goodsBaseInfo u-flex u-row-between u-col-top u-p-10">
							<view class="priceNum">
								<text class="title u-p-l-10 u-font-32">{{goods.shopName}}</text>
								<br>
								<!-- <text class="small">{{goods.shopDetails}}</text> -->
								<view class="u-text-right small">
									库存:<text style="color:red">{{goods.stock}}</text>
								</view>
							</view>
							<view class="priceNum u-flex u-row-between">
								<text class="price u-font-34">￥{{goods.price*goods.num}}</text>
								<u-number-box v-model="goods.num" :min="1" :max="goods.stock" :index="goods._id"
									:disabled-input="true" @change="numChange">
								</u-number-box>
								<u-icon @click="removeGoods(goods._id)" name="trash" color="#e83333" size="36">
								</u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="empty" v-else>
				<u-empty text="购物车空空如也" mode="car"></u-empty>
			</view>
			<view class="bottomFixed u-flex u-p-15">
				<view class="u-flex-5">
					<u-checkbox v-model="allCheck" size="40" shape="circle">全选</u-checkbox>
				</view>
				<view class="u-flex u-flex-5 u-row-around u-m-b-10">
					<view>
						<text class="title">合计:</text>
						<text class="price">￥{{totalPrice}}</text>
					</view>
					<!-- <u-button type="primary" :ripple="true" shape="square" disabled>去结算</u-button> -->
					<u-button type="primary" :ripple="true" shape="square" @click="toCreatOrder">去结算</u-button>
				</view>
			</view>

		</template>
		<template v-else>
			<u-empty text="暂未登入" mode="permission"></u-empty>
			<view class="tologin" @click="toLogin">点击去登录</view>
		</template>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cartList: [],
				isLogin: '',
				// allCheck: false,
				// isCheck: true,
				// goodsNum: 1,
				form: {
					tradeNo: '',
					goodsInOrder: [],
					payStatus: 0,
					totalFee: 0,
					username: '',
					backgoods: 0,
					acceptgoods: 0
				}
			};
		},
		onShow() {
			this.getCartList()
			this.getCartChecked()
			try {
				const username = uni.getStorageSync('username');
				if (username) {
					this.isLogin = username
					this.form.username = username
				}
			} catch (e) {
				// error
			}

		},

		onLoad() {

		},
		computed: {
			// 全选和全不选判断
			allCheck: {
				get() {
					return this.cartList.every((goods) => {
						return goods.isCheck
					})
				},
				set(val) {
					this.checkApi(val)

				}
			},
			// 选中商品的总价
			totalPrice() {
				return this.cartList.filter((goods) => { //过滤掉没有选中商品
					if (goods.isCheck) {
						return true
					}
				}).reduce((pre, goods) => { //价格累加
					return parseInt(pre) + parseInt(goods.price) * goods.num //乘商品数量
				}, 0)
			}
		},
		methods: {

			//获取购物车商品列表
			getCartList() {
				const username = uni.getStorageSync('username');
				uniCloud.callFunction({
					name: "cartList",
					data: {
						username: username
					}
				}).then(res => {
					this.cartList = res.result
				})
			},
			// 商品数量改变
			async numChange(e) {
				const db = uniCloud.database();
				const collection = await db.collection('goods-list').where({
					_id: e.index
				}).update({
					num: e.value
				})
				this.getCartChecked()

			},
			// 移出购物车
			async removeGoods(id) {
				const username = uni.getStorageSync('username');
				uniCloud.callFunction({
					name: 'remove-cart',
					data: {
						username: username,
						goods_id: id
					}
				}).then(res => {
					this.$u.toast('移除成功')
					this.getCartList()
					this.getCartChecked()
				})

			},
			// 单个商品是否选中
			async checkChange(val) {
				const db = uniCloud.database();
				const collection = await db.collection('goods-list').where({
					_id: val.name
				}).update({
					isCheck: val.value
				})
				this.getCartChecked()

			},
			// 全选与全不选接口调用
			async checkApi(val) {
				if (!val) {
					// 全选点击（变全不选）
					const username = uni.getStorageSync('username');
					uniCloud.callFunction({
						name: 'all-checked-f',
						data: {
							username: username
						}
					}).then(res => {
						console.log(res);
						// this.allCheck = false
						this.getCartList()
						this.getCartChecked()
					})
				} else {
					// 全不选选点击（变全选）
					const username = uni.getStorageSync('username');
					uniCloud.callFunction({
						name: 'all-checked-t',
						data: {
							username: username
						}
					}).then(res => {
						this.getCartList()
						this.getCartChecked()
					})
				}
			},
			//获取购物车中选中的商品列表
			getCartChecked() {
				const username = uni.getStorageSync('username');
				uniCloud.callFunction({
					name: "cart-checked",
					data: {
						username: username
					}
				}).then(res => {
					this.form.goodsInOrder = res.result.data
					// console.log(this.form.goodsInOrder);
				})
			},
			//创建订单
			toCreatOrder() {
				if (this.form.goodsInOrder.length == 0) {
					this.$u.toast('请选择要购买的商品')

				} else {
					this.form.totalFee = this.totalPrice
					this.form.tradeNo = this.$u.guid(20)
					uniCloud.callFunction({
						name: "creatOrder",
						data: {
							...this.form
						}
					}).then(res => {
						this.$u.route('/pages/createOrder/createOrder', {
							tradeNo: this.form.tradeNo
						});
					})

				}


			},
			toLogin() {
				type: 'reLaunch',
				this.$u.route('/pages/user/login');
			},

		},

	}
</script>

<style scoped lang="scss">
	.wrap {
		min-height: 80vh;

		.empty {
			height: 80vh;
		}

		.loading {
			text-align: center;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.title,
		.price {
			font-weight: 800;
		}

		.price {
			color: #e83333;
		}

		.cartcartList {
			.cartGoods {
				.goodsInfo {
					width: 100%;
					background-color: rgb(251, 250, 251);

					.goodsBaseInfo {
						width: 100%;
						height: 200rpx;
						flex-direction: column;

						.priceNum {
							width: 100%;

						}
					}
				}
			}
		}

		.bottomFixed {
			position: fixed;
			left: 0;
			right: 0;
			background-color: #fff;
		}

		/*#ifdef H5*/
		.bottomFixed {
			bottom: 100rpx;
		}

		/*#endif*/
		/*#ifdef MP-WEIXIN*/
		.bottomFixed {
			bottom: 0;
			z-index: 99999;
		}

		/*#endif*/
		.tologin {
			display: flex;
			justify-content: center;
			color: #1296db;
		}
	}
</style>
